﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Emerson.Storage.Entities;
using Emerson.Storage.Agent.Core;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Sockets;

namespace Emerson.Storage.Service
{
    public class    WorkstationUpdater
    {
        private Workstation _workstation;
        private ManualResetEvent _completedEvent;

        //public static void WaitAll(List<WorkstationUpdater> updaters, TimeSpan timeout)
        //{
        //    List<WaitHandle> handles = new List<WaitHandle>(updaters.Count);
        //    foreach (var ud in updaters)
        //    {
        //        handles.Add(ud.completedEvent);
        //    }

        //    WaitHandle.WaitAll(handles.ToArray());
        //}

        public WorkstationUpdater(Workstation workstation, ManualResetEvent completedEvent)
        {
            _workstation = workstation;
            _completedEvent = completedEvent;
        }

        public void DoUpdate()
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(this.DoUpdateInBackground), _workstation);
        }

        private void DoUpdateInBackground(object state)
        {
            Workstation curWorkstation = (Workstation)state;

            string ipAddress = _workstation.IPAddress.Trim();
            IAgentService agentService = AgentAccess.GetAgentService(ipAddress);

            try
            {
                List<BatteryInfo> bis = agentService.GetBatteryInfos();
                WorkstationInfo wi = agentService.GetWorkstationInfo();

                //curWorkstation.UpdateWorkstation(wi);
                curWorkstation.IsConnected = true;

                foreach (Battery bat in curWorkstation.Battery)
                {
                    //find the corresponding battery in batteryInfo list, currently we use battery Type 
                    //as the key because it is unique for every workstation.
                    BatteryInfo bi = bis.Find(b => b.BatteryType == bat.BatteryType);
                  //  if (bi != null)
                       // bat.UpdateBattery(bi);
                }
            }
            catch (SocketException se)
            {
                curWorkstation.IsConnected = false;
                foreach (Battery bat in curWorkstation.Battery)
                    bat.IsConnected = false;

                string msg = se.Message;
            }

            lock (_workstation)
            {
                _workstation = curWorkstation;
            }

            _completedEvent.Set();
        }

        public Workstation GetWorkstation()
        {
            return _workstation;
        }
    }
}
